<script lang="ts">
  import { Check, PenLine, X } from "lucide-svelte";
  import { getContext } from "svelte";
  import type { Store as ToastStore } from "@zag-js/toast";
  const toast: ToastStore = getContext("toast");

  interface Props {
    value: string;
    canEdit: boolean;
    maxWidthClass: string;
    onChange: (value: string) => Promise<boolean>;
    onClick?: () => void;
  }
  let props: Props = $props();

  let newValue = $state(props.value);

  let inEdit = $state(false);

  async function changeValue() {
    const ok = await props.onChange(newValue);
    if (ok == false) {
      newValue = props.value;
      toast.create({
        title: "失败",
        description: "设置失败!",
        type: "error",
      });
    } else {
      inEdit = false;
    }
  }
</script>

{#if inEdit == false}
  <div class="w-full flex gap-x-2 items-center">
    {#if props.onClick == undefined}
      <div class={`truncate ${props.maxWidthClass}`}>
        {props.value}
      </div>
    {:else}
      <button
        type="button"
        class="btn p-0 h-[1rem] hover:preset-tonal"
        onclick={() => props.onClick!()}
      >
        <div class={`truncate ${props.maxWidthClass}`}>
          {props.value}
        </div>
      </button>
    {/if}
    {#if props.canEdit}
      <button
        type="button"
        class="btn p-0 h-[1rem] hover:preset-tonal"
        onclick={() => {
          newValue = props.value;
          inEdit = true;
        }}
      >
        <PenLine size={16} />
      </button>
    {/if}
  </div>
{:else}
  <div class="w-full flex gap-x-2">
    <input
      bind:value={newValue}
      class={`${props.maxWidthClass.replaceAll("max-", "")} rounded-none bg-surface-100-900 input`}
    />
    <button
      type="button"
      class="btn text-success-800-200 p-0 hover:preset-tonal"
      onclick={() => changeValue()}
    >
      <Check />
    </button>
    <button
      type="button"
      class="btn text-error-800-200 p-0 hover:preset-tonal"
      onclick={() => {
        inEdit = false;
        newValue = props.value;
      }}
    >
      <X />
    </button>
  </div>
{/if}
